package com.dolawing.phonecallapp.keepAliveService;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.dolawing.phonecallapp.R;
import com.dolawing.phonecallapp.keepAliveService.IKeepAliveService;
import com.dolawing.phonecallapp.listenphonecall.CallListenerService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * content:后台运行的服务
 */
public class RemoteService extends Service {
    private MyConn conn;
    private MyBinder binder;
    private NotificationCompat.Builder builder;
    private int count = 0;
    private int notifyId =1;
    private IKeepAliveService iKeepAliveService;
    private boolean cycleFlag = true;  //循环标示
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //定时器
            new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        while(cycleFlag){
                            Calendar calendar = Calendar.getInstance();
                            int hour = calendar.get(Calendar.HOUR_OF_DAY);
                            int min = calendar.get(Calendar.MINUTE);
                            int sec = calendar.get(Calendar.SECOND);
                            String timestamps = ""+hour + "时" + min+"分" + sec +"秒";//记录时间
                            try {
                                Thread.sleep(1000);
//                                Log.i("startForeground","Running..."+timestamps+iKeepAliveService.getServiceName()+",累计="+iKeepAliveService.getCount());
                                StringBuffer stringBuffer = new StringBuffer();
                                stringBuffer.append("正在运行: "+timestamps);
                                stringBuffer.append(", 数量："+iKeepAliveService.getCount());
                                builder.setContentText(stringBuffer.toString());
//                                builder.setContentText("Running..."+timestamps+"Count="+iKeepAliveService.getCount()+",\n网络:"+iKeepAliveService.getNetWork() + ", 弹窗" + iKeepAliveService.getFlost());
                                startForeground(notifyId, builder.build());
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    };


    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        conn = new MyConn();
        binder = new MyBinder();
        //开启Notification
        startTo();

        //绑定 Service
        boolean flag = RemoteService.this.bindService(new Intent(RemoteService.this, CallListenerService.class),
                conn, Context.BIND_AUTO_CREATE);
        //绑定 成功
        if (flag){
            Log.i("RemoteService","绑定成功");
            Message msg = Message.obtain();
            handler.sendMessage(msg);
        }

        //Service启动，就开始计数
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    while(cycleFlag){
                        try {
                            count = (count+1)%36000;
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("在RemoteService服务...","onStartCommand方法执行");
        this.bindService(new Intent(RemoteService.this, CallListenerService.class),
                conn, Context.BIND_AUTO_CREATE);


        return START_STICKY;
    }

    private class MyBinder extends IKeepAliveService.Stub {
        @Override
        public String getServiceName() throws RemoteException {
            return RemoteService.class.getSimpleName();
        }

        @Override
        public int getCount() throws RemoteException {
            return count;
        }

    }

    private class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iKeepAliveService =IKeepAliveService.Stub.asInterface(service);
            try {
                Log.i("在RemoteService服务...","RemoteService与"+iKeepAliveService.getServiceName()+"建立链接");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            cycleFlag = false; //退出循环
            Intent intent = new Intent(RemoteService.this, CallListenerService.class);
            //开启本地服务
            if (Build.VERSION.SDK_INT >= 26) {
                //适配8.0机制
                RemoteService.this.startForegroundService(intent);
            } else {
                RemoteService.this.startService(intent);
            }
            //绑定本地服务
            RemoteService.this.bindService(new Intent(RemoteService.this, CallListenerService.class), conn, Context.BIND_AUTO_CREATE);
        }
    }

    private void startTo() {
        String CHANNEL_ID = "com.dolawing.phonecall.keepalive.RemoteService";
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel Channel = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Channel = new NotificationChannel(CHANNEL_ID, "Remote Service", NotificationManager.IMPORTANCE_LOW);
            Channel.enableLights(true);
            Channel.setLightColor(Color.RED);
            Channel.setShowBadge(true);
            Channel.setDescription("RemoteServiceId");
            Channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置锁屏可见 VISIBILITY_PUBLIC=可见
            manager.createNotificationChannel(Channel);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTimes = sdf.format(new Date());
        builder = new NotificationCompat.Builder(this,CHANNEL_ID)
                .setContentTitle("诉事速办: 守护进程")//标题
                .setContentText("Running...")//内容
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background);//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
        notification = builder.build();
        //让通知显示出来 第一个参数是id，要保证每个通知所指定的id各不相同 第二个参数是Notification对象
        manager.notify(notifyId, notification);
        // startForeground(notifyId, builder.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cycleFlag = false;
        Log.i("在RemoteService服务...","onDestroy被执行");
    }

    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = null;
        if (myAM != null) {
            myList = myAM.getRunningServices(Integer.MAX_VALUE);
        }
        if (myList != null && myList.size() <= 0) {
            return false;
        }
        if (myList != null) {
            for (int i = 0; i < myList.size(); i++) {
                String mName = myList.get(i).service.getClassName();
                if (mName.equals(serviceName)) {
                    isWork = true;
                    break;
                }
            }
        }
        return isWork;

    }


}
